/**
 * @Description:
 * @Author HP
 * @create 2021/8/20 9:49
 */
import { make } from '../plugins/vuex-helper'
import appConfig from '/src/config/'
import { parseJSONNoError } from '/src/utils/common'
import api from '/src/api'

const { user } = parseJSONNoError(localStorage.getItem('system_info')) || {}

const state = {
  timestamp: '时间戳',
  info: {}, // 用户信息
  appPermissions: [],
  commPermissions: [],
  tokenType: 'bearer', // token_type
  accessToken: user?.accessToken, // token
  refreshToken: user?.refreshToken // 暂时没用到，保留
}

const mutations = {
  ...make.mutations(state)
}

// timestamp(state, data) {
//s }

const actions = {
  /**
   * 跳转第三方统一登录页
   */
  loginToThirdParty() {
    const prefix = `http://${appConfig.single_login_uri}`
    window.location.href = `${prefix}/auth/oauth/authorize?client_id=${appConfig.client_id}&redirect_uri=http://${window.location.host}/authorization&response_type=${appConfig.login_res_type}`
  },

  /**
   * 获取token
   * @returns {Promise<boolean>}
   */
  async getAccessToken({ commit }, code = '') {
    const sendData = {
      params: {
        grant_type: 'authorization_code',
        code: code,
        redirect_uri: `http://${window.location.host}/authorization`
      }
    }
    const res = await api.authLoginByCode(sendData)
    commit('refreshToken', res.refresh_token)
    commit('accessToken', res.access_token)
  },

  /**
   * 获取用户信息
   */
  async getUserInfo({ commit }) {
    const res = await api.authGetUserInfo()
    console.log('获取用户信息', res)
    if (res.code == 200) {
      const { sysUser, commPermissions, appPermissions } = res.data
      commit('info', sysUser)
      commit('commPermissions', commPermissions)
      commit('appPermissions', appPermissions)
    }
    return res.data
  },

  /**
   * 退出登录
   */
  async logOut({ commit, dispatch }) {
    // 这里要调用退出登录接口
    commit('info', {})
    commit('accessToken', null)
    commit('refreshToken', null)
    dispatch('loginToThirdParty')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
